using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Xml;
using System.Drawing;
using System.Collections;
using PluginCore.Controls;
using System.Text.RegularExpressions;

namespace haxeProject
{
	public class TipThread
	{
		Process p;
		Thread t;
		public int pos;
		public ScintillaNet.ScintillaControl sci;
		public String data;
		public String type;
		public ArrayList tips;
		
		public TipThread( ScintillaNet.ScintillaControl sci, String cmd, String args ) {
			this.sci = sci;
			pos = sci.CurrentPos;
			p = new Process();
			p.StartInfo.FileName = cmd;
			p.StartInfo.Arguments = args;
			p.StartInfo.UseShellExecute = false;
			p.StartInfo.RedirectStandardError = true;
			p.StartInfo.CreateNoWindow = true;
			p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
			p.EnableRaisingEvents = true;
		}
		
		public void start() {
			t = new Thread(new ThreadStart(run));
			t.Start();
		}
		
		private void run() {
			try {
				loop();
			} catch( Exception e ) {
				data = "";
				Dialog.Error(e.ToString());
			}
		}
		
		private String htmlUnescape( String s ) {
			return s.Replace("&lt;","<").Replace("&gt;",">");
		}
		
		private void loop() {
			p.Start();
			string[] lines = p.StandardError.ReadToEnd().Split('\n');
			string errors = "";
			for( int i=0;i<lines.Length;i++) {
				String l = lines[i].Trim('\r');
				if( l.Length == 0 )
					continue;
				if( l == "<list>" ) {
					tips = new ArrayList();
					string xml = "";
					while( ++i < lines.Length )
						xml += lines[i];					
					foreach( Match m in Regex.Matches(xml,"<i n=\"([^\"]+)\"><t>([^<]*)</t><d>([^<]*)</d></i>") )
						tips.Add(new Tip(m.Groups[1].Value,htmlUnescape(m.Groups[2].Value),htmlUnescape(m.Groups[3].Value)));
					break;
				}
				if( l == "<type>" ) {
					type = htmlUnescape(lines[++i].Trim('\r'));
					break;
				}
				if( errors == "" )
					errors = l;
				else if( lines[i] != "" && lines[i] != "\r" )
					errors = errors + "\n" + l;
			}
			data = errors;
			p.Close();
		}

		private class Tip : ICompletionListItem {
			
			private String name;
			private String type;
			private String desc;
			
			public Tip( String name, String type, String desc ) {
				this.name = name;
				this.type = type;
				this.desc = desc;
			}
			
			public string Label {
				get { return name; }
			}
			
			public string Description {
				get { 
					if( type != "" )
						return type+"\n"+desc;
					return desc;
				}
			}
			
			public System.Drawing.Bitmap Icon {
				get { 
					bool isMethod = type.IndexOf("->") != -1;
					Image img = (isMethod?Icons.TIP_METHOD:Icons.TIP_MEMBER).image;
					return (Bitmap)img;
				}
			}
			
			public string Value { 
				get { return name; }
			}
		}

	}

}
